import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const PORT = 8080;
const DIST_DIR = path.join(__dirname, 'dist');

// MIME类型映射
const mimeTypes = {
  '.html': 'text/html',
  '.js': 'application/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.ico': 'image/x-icon'
};

function getMimeType(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  return mimeTypes[ext] || 'application/octet-stream';
}

const server = http.createServer((req, res) => {
  // 移除查询参数
  let filePath = req.url.split('?')[0];
  
  // 默认返回index.html
  if (filePath === '/') {
    filePath = '/index.html';
  }
  
  const fullPath = path.join(DIST_DIR, filePath);
  
  // 检查文件是否存在
  fs.access(fullPath, fs.constants.F_OK, (err) => {
    if (err) {
      res.writeHead(404);
      res.end('File not found');
      return;
    }
    
    // 读取并返回文件
    fs.readFile(fullPath, (err, data) => {
      if (err) {
        res.writeHead(500);
        res.end('Internal server error');
        return;
      }
      
      const mimeType = getMimeType(fullPath);
      res.writeHead(200, { 'Content-Type': mimeType });
      res.end(data);
    });
  });
});

server.listen(PORT, () => {
  console.log(`\n🚀 本地服务器已启动!`);
  console.log(`📱 访问地址: http://localhost:${PORT}`);
  console.log(`📁 服务目录: ${DIST_DIR}`);
  console.log(`\n💡 提示: 按 Ctrl+C 停止服务器`);
  console.log(`\n如果构建文件不存在，请先运行: npm run build`);
});